const db = require('../db/database');

class Event {
  // 获取所有事件（分页）- 来自第三部分
  static getAll(page = 1, limit = 10) {
    const offset = (page - 1) * limit;
    return new Promise((resolve, reject) => {
      db.all(
        `SELECT * FROM events ORDER BY created_at DESC LIMIT ? OFFSET ?`,
        [limit, offset],
        (err, rows) => {
          if (err) reject(err);
          resolve(rows);
        }
      );
    });
  }

  // 按状态获取事件 - 来自第三部分
  static getByStatus(status) {
    return new Promise((resolve, reject) => {
      db.all(
        `SELECT * FROM events WHERE status = ? ORDER BY created_at DESC`,
        [status],
        (err, rows) => {
          if (err) reject(err);
          resolve(rows);
        }
      );
    });
  }
  
  // 获取单个事件详情 - 来自第二部分
  static getById(id) {
    return new Promise((resolve, reject) => {
      db.get(
        `SELECT * FROM events WHERE id = ?`,
        [id],
        (err, row) => {
          if (err) reject(err);
          resolve(row);
        }
      );
    });
  }
  
  // 创建新事件 - 来自第二部分
  static create(title, description, severity = 'medium') {
    return new Promise((resolve, reject) => {
      db.run(
        `INSERT INTO events (title, description, severity) VALUES (?, ?, ?)`,
        [title, description, severity],
        function(err) {
          if (err) reject(err);
          resolve(this.lastID);
        }
      );
    });
  }
  
  // 确认事件 - 来自第二部分
  static acknowledge(id, userId) {
    return new Promise((resolve, reject) => {
      const timestamp = new Date().toISOString();
      db.run(
        `UPDATE events SET 
          status = 'acknowledged', 
          acknowledged_by = ?, 
          acknowledgement_time = ?,
          updated_at = ?
         WHERE id = ?`,
        [userId, timestamp, timestamp, id],
        function(err) {
          if (err) reject(err);
          resolve(this.changes);
        }
      );
    });
  }
  
  // 解决事件 - 来自第二部分
  static resolve(id, userId) {
    return new Promise((resolve, reject) => {
      const timestamp = new Date().toISOString();
      db.run(
        `UPDATE events SET 
          status = 'resolved', 
          resolved_by = ?, 
          resolution_time = ?,
          updated_at = ?
         WHERE id = ?`,
        [userId, timestamp, timestamp, id],
        function(err) {
          if (err) reject(err);
          resolve(this.changes);
        }
      );
    });
  }
  
  // 获取待处理事件 - 来自第二部分
  static getPending() {
    return new Promise((resolve, reject) => {
      db.all(
        `SELECT * FROM events WHERE status = 'pending' ORDER BY created_at DESC`,
        (err, rows) => {
          if (err) reject(err);
          resolve(rows);
        }
      );
    });
  }
}

module.exports = Event;